package com.example.usermanagement.service.impl;

import com.example.usermanagement.dto.request.UserAddRequest;
import com.example.usermanagement.dto.request.UserQueryRequest;
import com.example.usermanagement.dto.request.UserUpdateRequest;
import com.example.usermanagement.dto.response.PageResponse;
import com.example.usermanagement.dto.response.UserResponse;
import com.example.usermanagement.entity.SysUser;
import com.example.usermanagement.exception.BusinessException;
import com.example.usermanagement.mapper.SysUserMapper;
import com.example.usermanagement.service.SysUserService;
import com.example.usermanagement.util.PasswordUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl implements SysUserService {


    // src/main/java/com/example/usermanagement/service/impl/SysUserServiceImpl.java
    @Override
    public SysUser getUserByUsername(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserResponse getUserById(Long id) {
        if (id == null) {
            throw new BusinessException("用户ID不能为空");
        }

        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser == null) {
            throw new BusinessException("用户不存在");
        }

        return convertToUserResponse(sysUser);
    }

    @Override
    public PageResponse<UserResponse> getUserList(UserQueryRequest queryRequest) {
        // 计算分页偏移量
        int pageNum = queryRequest.getPageNum();
        int pageSize = queryRequest.getPageSize();
        queryRequest.setPageNum((pageNum - 1) * pageSize);

        // 查询数据
        List<SysUser> userList = sysUserMapper.selectList(queryRequest);
        int total = sysUserMapper.selectCount(queryRequest);

        // 转换为响应DTO
        List<UserResponse> userResponses = userList.stream()
                .map(this::convertToUserResponse)
                .collect(Collectors.toList());

        // 构建分页响应
        PageResponse<UserResponse> pageResponse = new PageResponse<>();
        pageResponse.setList(userResponses);
        pageResponse.setTotal(total);
        pageResponse.setPageNum(pageNum);
        pageResponse.setPageSize(pageSize);
        pageResponse.setPages((total + pageSize - 1) / pageSize); // 计算总页数

        return pageResponse;
    }

    @Transactional
    @Override
    public Long addUser(UserAddRequest userAddRequest) {
        // 1. 校验用户名重复
        SysUser existingUser = sysUserMapper.selectByUsername(userAddRequest.getUsername());
        if (existingUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 2. 复制参数（此时status已有默认值1）
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userAddRequest, sysUser);

        // 3. 密码加密（调用工具类）
        sysUser.setPassword(PasswordUtils.md5Encrypt(sysUser.getPassword()));

        // 4. 插入数据库（无需手动设置createTime，XML中用NOW()）
        sysUserMapper.insert(sysUser);

        return sysUser.getId();
    }

    @Transactional
    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest) {
        Long id = userUpdateRequest.getId();
        if (id == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 检查用户是否存在
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 检查用户名是否已被其他用户使用
        if (userUpdateRequest.getUsername() != null &&
                !userUpdateRequest.getUsername().equals(sysUser.getUsername())) {
            SysUser existingUser = sysUserMapper.selectByUsername(userUpdateRequest.getUsername());
            if (existingUser != null) {
                throw new BusinessException("用户名已存在");
            }
        }

        // 复制更新字段
        BeanUtils.copyProperties(userUpdateRequest, sysUser);

        // 如果更新密码，则进行加密处理
        if (userUpdateRequest.getPassword() != null && !userUpdateRequest.getPassword().isEmpty()) {
            sysUser.setPassword(PasswordUtils.md5Encrypt(userUpdateRequest.getPassword()));
        }

        // 更新数据库
        int rows = sysUserMapper.update(sysUser);
        return rows > 0;
    }

    @Transactional
    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 检查用户是否存在
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 删除用户
        int rows = sysUserMapper.deleteById(id);
        return rows > 0;
    }

    /**
     * 转换实体类到响应DTO
     */
    private UserResponse convertToUserResponse(SysUser sysUser) {
        UserResponse userResponse = new UserResponse();
        BeanUtils.copyProperties(sysUser, userResponse);
        // 密码不返回
        userResponse.setStatus(sysUser.getStatus()); // 触发状态描述设置
        return userResponse;
    }
}
